package com.zhongxi.guoyuan.view.personalCenter;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.PermissionChecker;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;


import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ExchangeGoodAttrAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedDetailResult;
import com.zhongxi.guoyuan.entity.coinStore.AttrItemBean;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.GoodsAttrCollections;
import com.zhongxi.guoyuan.fragment.clearweeddetail.ClearweedCommentFragment;
import com.zhongxi.guoyuan.fragment.clearweeddetail.ClearweedDetailFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonBaiduMap;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.view.PlayActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClearWeedDetailActivity extends BaseActivity {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.clearWeed_detail_share)
    LinearLayout clearWeedDetailShare;
    @Bind(R.id.clearWeed_detail_pay)
    RelativeLayout clearWeedDetailPay;
    @Bind(R.id.linear_bottom)
    LinearLayout linearBottom;
    @Bind(R.id.clearWeed_detail_banner)
    Banner clearWeedDetailBanner;
    @Bind(R.id.clearWeed_detail_name)
    TextView clearWeedDetailName;
    @Bind(R.id.clearWeed_detail_original)
    TextView clearWeedDetailOriginal;
    @Bind(R.id.clearWeed_detail_sales)
    TextView clearWeedDetailSales;
    @Bind(R.id.clearWeed_detail_exchangeTip)
    TextView clearWeedDetailExchangeTip;
    @Bind(R.id.clearWeed_detail_beanNum)
    TextView clearWeedDetailBeanNum;
    @Bind(R.id.clearWeed_detail_redbean)
    TextView clearWeedDetailRedBean;
    @Bind(R.id.clearWeed_detail_stock)
    TextView clearWeedDetailStock;
    @Bind(R.id.clearWeed_detail_declare)
    TextView clearWeedDetailDeclare;
    @Bind(R.id.clearWeed_detail_limit)
    TextView clearWeedDetailLimit;
    @Bind(R.id.clearWeed_detail_content)
    TextView clearWeedDetailContent;
    @Bind(R.id.subscrib_address_tip)
    TextView subscribAddressTip;
    @Bind(R.id.iv_goshopping)
    ImageView ivGoshopping;
    @Bind(R.id.clearWeed_detail_shopName)
    TextView clearWeedDetailShopName;
    @Bind(R.id.clearWeed_detail_call)
    TextView clearWeedDetailCall;
    @Bind(R.id.iv_phone)
    ImageView ivPhone;
    @Bind(R.id.clearWeed_detail_shopPhone)
    TextView clearWeedDetailShopPhone;
    @Bind(R.id.iv_position)
    ImageView ivPosition;
    @Bind(R.id.clearWeed_detail_navigation)
    TextView clearWeedDetailNavigation;
    @Bind(R.id.clearWeed_detail_shopAddress)
    TextView clearWeedDetailShopAddress;
    @Bind(R.id.clearWeed_detail_scrollView)
    MyScrollView clearWeedDetailScrollView;
    @Bind(R.id.tv_clearDetail_evaluate)
    TextView tvEvaluate;
    @Bind(R.id.clearweed_detail_postage)
    TextView postage;
    @Bind(R.id.clearweed_detail_btComment)
    TextView btComment;
    @Bind(R.id.clearweed_detail_btDetail)
    TextView btDetail;
    @Bind(R.id.clearweed_detail_relaContainer)
    RelativeLayout relaContainer;
    @Bind(R.id.clearweed_detail_beandeclare)
    TextView mBeanDeclare;
    @Bind(R.id.clearweed_detail_reward)
    TextView mRewardtip;
    ClearWeedDetailResult detailResult;
    @Bind(R.id.view)
    View mView;
    List<String> imageList;
    private ClearWeedDetailResult.GoodsInfoBean goodsInfo;
    private ClearWeedDetailResult.ShopInfoBean shopInfo;
    private static int REQUEST_CODE = 1000;
    private String phone;

    private SHARE_MEDIA platform;
    private EditText etNum;
    private EditText exist;
    private String trim;
    private TextView price;
    private TextView tvRedBean;
    private int purchasingnum;
    private String type;

    private String id;

    int num = 1;//商品数量
    int totalRedBean;//商品总红豆数
    private JSONObject user;


    private ProgressDialog progressDialog;

    private List<GoodsAttrCollections> attrCollectionses;
    private JSONObject attr;
    private List<List<AttrItemBean>> itemAttrList;
    private Map<String, List<AttrItemBean>> mapAllAttrs;
    private ExchangeGoodAttrAdapter exchangeGoodAttrAdapter;
    private boolean isSameAttrKey;
    private ArrayList<String> attrKeyList;
    private Map<String, List<String>> maps;
    private ArrayList<AttrsSelect> allList;
    private ImageView ivImg;
    private TextView tvInventory;
    private TextView tvAward;
    private TextView tvDayLimit;
    private TextView tvTotalLimit;
    private TextView tv_price;
    private TextView tv_redprice;


    boolean stateType1, stateType2, stateType3;  //同城,自提,邮寄

    private String goodsInfoName;

    private ClearweedCommentFragment mCommentFragment;
    private ClearweedDetailFragment mDetailFragment;
    private View popupWindow_view;
    private PopupWindow popupWindow;
    private int mFlag;


    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_clear_weed_detail);
        ButterKnife.bind(this);
        tvTitle.setText("豆豆兑换商品详情");
        initBanner();
        mFlag = getIntent().getIntExtra("flag", 0);
        ImageUtils.setHeight(this, Constants.flowRate, clearWeedDetailBanner);


    }

    private void initFragment() {

        mDetailFragment = new ClearweedDetailFragment();
        mCommentFragment = new ClearweedCommentFragment(id);

        fragments = new android.support.v4.app.Fragment[]{mDetailFragment, mCommentFragment};

        btDetail.setSelected(true);
        btComment.setSelected(false);

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.clearweed_detail_relaContainer, mDetailFragment)
                .commit();
    }

    private void initBanner() {
        clearWeedDetailBanner.isAutoPlay(true);
        clearWeedDetailBanner.setDelayTime(3000);
        clearWeedDetailBanner.setIndicatorGravity(BannerConfig.CENTER);

    }

    @Override
    protected void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        imageList = new ArrayList<>();
        getDetailData();
        initFragment();
    }

    /***
     * 获取详细信息
     */
    private void getDetailData() {
        type = "detail";
        String str = "&gid=" + id;
        getServer(Url.CLEARWEED_DETAIL, null, str, false, null, "get");
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        clearWeedDetailScrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {

            }

            @Override
            public void scrollBottom() {

            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("detail")) {
            detailResult = gson.fromJson(response, ClearWeedDetailResult.class);
            MyApplication.getInstance().setSpValue(detailResult.getSafeobj());

            if (null != detailResult && !"".equals(detailResult)) {
                goodsInfo = detailResult.getGoodsInfo();
                shopInfo = detailResult.getShopInfo();
                purchasingnum = detailResult.getPurchasingnum();
                if (null != goodsInfo && !"".equals(goodsInfo)) {
                    initGoodsInfo();
                }
                if (null != shopInfo && !"".equals(shopInfo)) {
                    initShopInfo(shopInfo);
                }
            }

            if (detailResult.getGoodsAttrCollection() != null && !"".equals(detailResult.getGoodsAttrCollection())) {
                attrCollectionses = detailResult.getGoodsAttrCollection();
            }

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            attr = jsonObject.optJSONObject("attrList");
            JSONArray attrKeyjson = jsonObject.optJSONArray("attrKey");//  "["汽车型号","形状","汽油型号","汽车牌照"]"
            attrKeyList = new ArrayList<>();
            for (int i = 0; i < attrKeyjson.length(); i++) {
                String e = null;
                try {
                    e = (String) attrKeyjson.get(i);
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                attrKeyList.add(e);
            }
            maps = new HashMap<>();
            if (attr != null && !"".equals(attr)) {
                Iterator<String> keys = attr.keys();
                while (keys.hasNext()) {
                    String next = keys.next();
                    JSONArray jsonArray = attr.optJSONArray(next);
                    List<String> attrIdList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                            for (int j = 0; j < jsonArray1.length(); j++) {
                                if (j == 1) {
                                    String attrid = (String) jsonArray1.get(1);
                                    attrIdList.add(attrid);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    maps.put(next, attrIdList);
                }
            }
            allList = new ArrayList<>();
            JSONArray jsonArray2 = jsonObject.optJSONArray("goodsAttrCollection");
            for (int i = 0; i < jsonArray2.length(); i++) {
                JSONObject jsonObject1 = null;
                try {
                    jsonObject1 = (JSONObject) jsonArray2.get(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AttrsSelect attrsSelect = new AttrsSelect();
                String price = jsonObject1.optString("innerprice");
                String redprice = jsonObject1.optString("redbean");
                String thumbnail = jsonObject1.optString("thumbnail");
                String goodsid = jsonObject1.optString("goodsid");
                String id = jsonObject1.optString("id");
                String stocknum = jsonObject1.optString("stocknum");
                String backcashnum = jsonObject1.optString("backcashnum");
                JSONObject object = jsonObject1.optJSONObject("newattr");
                Map<String, List<String>> itemAttrMap = new HashMap<>();
                if (object != null && !"".equals(object)) {
                    Iterator<String> keys = object.keys();
                    while (keys.hasNext()) {
                        String next = keys.next();
                        JSONArray jsonArray = object.optJSONArray(next);
                        List<String> attr = new ArrayList<>();
                        if (jsonArray != null && jsonArray.length() > 0) {
                            for (int j = 0; j < jsonArray.length(); j++) {
                                try {
                                    attr.add((String) jsonArray.get(j));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            itemAttrMap.put(next, attr);
                        }
                    }
                }
                attrsSelect.setPrice(price);
                attrsSelect.setRedprice(redprice);
                attrsSelect.setThumbnail(thumbnail);
                attrsSelect.setItemMaps(itemAttrMap);
                attrsSelect.setGoodsid(goodsid);
                attrsSelect.setId(id);
                attrsSelect.setStocknum(stocknum);
                attrsSelect.setBackcashnum(backcashnum);
                attrsSelect.setShopName(detailResult.getShopInfo().getName());
                attrsSelect.setShopId(detailResult.getShopInfo().getId());
                attrsSelect.setPhone(detailResult.getShopInfo().getPhone());
                attrsSelect.setAddress(detailResult.getShopInfo().getAddress());
                attrsSelect.setAmountofmail(detailResult.getShopInfo().getAmountofmail());
                allList.add(attrsSelect);
            }

        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        if (baseResponse.getCode() == 1000) {
            showShortToast("参数错误");
        } else if (baseResponse.getCode() == 1001) {
            showShortToast("用户未登录");
        } else if (baseResponse.getCode() == 1201) {
            showShortToast("店铺已关闭");
            finish();
        } else if (baseResponse.getCode() == 1202) {
            showShortToast("商品数量超出每日限额");
        } else if (baseResponse.getCode() == 2001) {
            showShortToast("库存不足");
        } else if (baseResponse.getCode() == 1691) {
            showShortToast("商品已下架");
            finish();
        } else if (baseResponse.getCode() == 4003) {
            showShortToast("密码错误");
        } else if (baseResponse.getCode() == 5003) {
            showShortToast("美豆不足");
        }
    }

    /***
     * 设置店铺信息
     * @param shopInfo
     */
    private void initShopInfo(ClearWeedDetailResult.ShopInfoBean shopInfo) {
        if (null != shopInfo.getName() && !"".equals(shopInfo.getName())) {
            clearWeedDetailShopName.setText(shopInfo.getName());
        } else {
            clearWeedDetailShopName.setText("");
        }
        if (null != shopInfo.getPhone() && !"".equals(shopInfo.getPhone())) {
            clearWeedDetailShopPhone.setText(shopInfo.getPhone());
        } else {
            clearWeedDetailShopPhone.setText("");
        }
        if (null != shopInfo.getAddress() && !"".equals(shopInfo.getAddress())) {
            clearWeedDetailShopAddress.setText(shopInfo.getAddress());
        } else {
            clearWeedDetailShopAddress.setText("");
        }
        if (null != shopInfo.getAmountofmail() && "0".equals(shopInfo.getAmountofmail())) {
            postage.setVisibility(View.VISIBLE);
        } else {
            postage.setVisibility(View.GONE);
        }
    }

    /***
     * 设置商品信息
     */
    private void initGoodsInfo() {

        if (null != goodsInfo.getName() && !"".equals(goodsInfo.getName())) {
            goodsInfoName = goodsInfo.getName();
            clearWeedDetailName.setText(goodsInfoName);
        } else {
            clearWeedDetailName.setText("");
        }

        if (null != goodsInfo.getMarketprice() && !"".equals(goodsInfo.getMarketprice())) {
            clearWeedDetailOriginal.setText("原价：" + goodsInfo.getMarketprice() + "元");
            clearWeedDetailOriginal.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            clearWeedDetailOriginal.setText("");
        }
        if (null != goodsInfo.getOrdernum() && !"".equals(goodsInfo.getOrdernum())) {
            clearWeedDetailSales.setText("销量：" + goodsInfo.getOrdernum());
        } else {
            clearWeedDetailSales.setText("");
        }

        if (DataUtil.moreThanZero(goodsInfo.getInnerprice()) && DataUtil.moreThanZero(goodsInfo.getRedbeanprice())) {
            clearWeedDetailBeanNum.setText(goodsInfo.getInnerprice() + "美豆");
            clearWeedDetailRedBean.setText(" + " + goodsInfo.getRedbeanprice() + "红豆");
            totalRedBean = Integer.parseInt(goodsInfo.getRedbeanprice());
            mView.setVisibility(View.GONE);
            mRewardtip.setVisibility(View.VISIBLE);
            if (DataUtil.moreThanZero(goodsInfo.getBackcashnum())) {
                mRewardtip.setText("红豆不够现金补,兑成奖：" + goodsInfo.getBackcashnum() + "元");
            } else {
                mRewardtip.setText("红豆不够现金补");
            }
        } else if (DataUtil.moreThanZero(goodsInfo.getInnerprice()) && !DataUtil.moreThanZero(goodsInfo.getRedbeanprice())) {
            clearWeedDetailBeanNum.setText(goodsInfo.getInnerprice() + "美豆");
            clearWeedDetailRedBean.setText("");
            if (DataUtil.moreThanZero(goodsInfo.getBackcashnum())) {
                mView.setVisibility(View.GONE);
                mRewardtip.setVisibility(View.VISIBLE);
                mRewardtip.setText("兑成奖：" + goodsInfo.getBackcashnum() + "元");
            } else {
                mView.setVisibility(View.VISIBLE);
                mRewardtip.setVisibility(View.GONE);
            }
        } else if (!DataUtil.moreThanZero(goodsInfo.getInnerprice()) && DataUtil.moreThanZero(goodsInfo.getRedbeanprice())) {
            clearWeedDetailBeanNum.setText("");
            clearWeedDetailRedBean.setText(goodsInfo.getRedbeanprice() + "红豆");
            totalRedBean = Integer.parseInt(goodsInfo.getRedbeanprice());
            mView.setVisibility(View.GONE);
            mRewardtip.setVisibility(View.VISIBLE);
            if (DataUtil.moreThanZero(goodsInfo.getBackcashnum())) {
                mRewardtip.setText("红豆不够现金补,兑成奖：" + goodsInfo.getBackcashnum() + "元");
            } else {
                mRewardtip.setText("红豆不够现金补");
            }
        } else {
            clearWeedDetailBeanNum.setText("");
            clearWeedDetailRedBean.setText("");
            mView.setVisibility(View.VISIBLE);
            mRewardtip.setVisibility(View.GONE);
        }

        if (null != goodsInfo.getLaststocknum() && !"".equals(goodsInfo.getLaststocknum())) {
            clearWeedDetailStock.setText("库存：" + goodsInfo.getLaststocknum());
        } else {
            clearWeedDetailStock.setText("");
        }
        if (null != goodsInfo.getDaylimit() && !"".equals(goodsInfo.getDaylimit())) {
            clearWeedDetailLimit.setText("每天限" + goodsInfo.getDaylimit() + "份");
        } else {
            clearWeedDetailLimit.setText("");
        }
        if (null != goodsInfo.getSubject() && !"".equals(goodsInfo.getSubject())) {
            clearWeedDetailContent.setText(goodsInfo.getSubject());
        } else {
            clearWeedDetailContent.setText("");
        }
        if (null != goodsInfo.getImages() && !"".equals(goodsInfo.getImages())) {
            for (int i = 0; i < goodsInfo.getImages().size(); i++) {
                String url = goodsInfo.getImages().get(i).endsWith(".mp4") ?
                        Url.IMG_URL + goodsInfo.getImages().get(i) + "?vframe/jpg/offset/10/w/640/h/360" : Url.IMG_URL + goodsInfo.getImages().get(i);
                imageList.add(url);
            }
            clearWeedDetailBanner.setImages(imageList).setImageLoader(new GlideImageLoader()).start();
            clearWeedDetailBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (goodsInfo.getImages().get(position).endsWith(".mp4")) {
                        Intent intent = new Intent(ClearWeedDetailActivity.this, PlayActivity.class);
                        intent.putExtra("url", goodsInfo.getImages().get(position));
                        startActivity(intent);
                    }
                }
            });

        }
        if (null != goodsInfo.getDesc() && !"".equals(goodsInfo.getDesc())) {
            mDetailFragment.ResultData(goodsInfo.getDesc());
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (4 == mFlag) {
            startAct(MainHomeActivity.class);
        }
    }

    @OnClick({R.id.ivBack, R.id.clearWeed_detail_share, R.id.clearWeed_detail_pay,
            R.id.clearWeed_detail_call, R.id.clearWeed_detail_navigation, R.id.clearweed_detail_beandeclare,
            R.id.clearweed_detail_btComment, R.id.clearweed_detail_btDetail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                if (4 == mFlag) {
                    startAct(MainHomeActivity.class);
                }
                break;
            case R.id.clearWeed_detail_share:
                initPopuWindow();
                break;
            case R.id.clearWeed_detail_pay:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    initAttrPopupWindow(1);
                } else {
                    startAct(LoginActivity.class);
                }

                break;
            case R.id.clearWeed_detail_call:
                if (null != shopInfo.getPhone() && !"".equals(shopInfo.getPhone())) {
                    phone = shopInfo.getPhone();
                    requestCallphone(phone);
                }
                break;
            case R.id.clearweed_detail_btDetail:

                btDetail.setSelected(true);
                btComment.setSelected(false);
                switchFragment(0);
                break;
            case R.id.clearweed_detail_btComment:

                btComment.setSelected(true);
                btDetail.setSelected(false);
                switchFragment(1);
                break;
            case R.id.clearWeed_detail_navigation://导航

                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(this);
                }
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //样式为圆形
                progressDialog.setCancelable(false);
                progressDialog.setOnKeyListener(keyListener);
                progressDialog.setMessage("正在获取数据,请稍后...");
                progressDialog.show();

                CommonBaiduMap mCommonBaiduMap = new CommonBaiduMap(ClearWeedDetailActivity.this, this, shopInfo.getLongitude()
                        , shopInfo.getLatitude(), shopInfo.getName(), "6", progressDialog);
                mCommonBaiduMap.startNavigate();
                break;
            case R.id.clearweed_detail_beandeclare:
                Intent intent = new Intent(context, HtmlActivity.class);
                intent.putExtra("type", "doudouRule");
                startActivity(intent);
                break;
        }
    }

    private int currentIndex = 0;
    private android.support.v4.app.Fragment[] fragments;

    private void switchFragment(int index) {

        if (index != currentIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (fragments[currentIndex].isAdded()) {
                trx.hide(fragments[currentIndex]);
            }
            if (!fragments[index].isAdded()) {
                trx.add(R.id.clearweed_detail_relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
            currentIndex = index;
        }
    }

    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == keyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
            return false;
        }
    };

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
        }
    }

    //获取权限
    private void requestCallphone(String phone) {
        if (Build.VERSION.SDK_INT >= 23) {
            //判断有没有拨打权限
            if (PermissionChecker.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE);
            } else {
                callPhone(phone);
            }
        } else {
            callPhone(phone);
        }
    }

    private void callPhone(String phone) {
        Uri uri = Uri.parse("tel:" + phone);
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            startActivity(intent);
        }
    }

    boolean isRemove = false;

    private void initAttrPopupWindow(final int flag) {
        final Map<String, AttrItemBean> selectAttrMap = new HashMap<>();
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                AttrItemBean attrItemBean = (AttrItemBean) msg.getData().getSerializable("attrItemBean");
                String attrId = attrItemBean.getAttrId();
                for (String attrKey : maps.keySet()) {
                    List<String> list = maps.get(attrKey);
                    for (int i = 0; i < list.size(); i++) {
                        if (attrId.equals(list.get(i))) {  //找到相应的key
                            if (selectAttrMap != null) {
                                if (selectAttrMap.size() > 0) {
                                    Iterator<String> iterator = selectAttrMap.keySet().iterator();
                                    while (iterator.hasNext()) {
                                        String next = iterator.next();
                                        AttrItemBean mapValue = selectAttrMap.get(next);
                                        if (mapValue.getAttrId().equals(attrId)) {   //去除属性
                                            iterator.remove();
                                            isRemove = true;
                                            break;
                                        }
                                    }
                                    if (isRemove) {  //去除属性
                                        if (selectAttrMap.size() > 0) {
                                            if (selectAttrMap.size() == 1) {
                                                Map.Entry<String, AttrItemBean> next = selectAttrMap.entrySet().iterator().next();
                                                String key = next.getKey();
                                                AttrItemBean value = next.getValue();
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(value, key);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                exchangeGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            } else {
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                exchangeGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            }
                                        } else {  //无点击,恢复正常
                                            itemAttrList = DataUtil.updataAdapter(itemAttrList);
                                            exchangeGoodAttrAdapter.notifyDataSetChanged();
                                            selectAttrMap.clear();
                                            isRemove = false;
                                            getItemClickChangePic();
                                            return;
                                        }
                                    } else {  //不去除属性
                                        for (String selectKey : selectAttrMap.keySet()) {
                                            if (attrKey.equals(selectKey)) {  //同一类点击切换
                                                isSameAttrKey = true;
                                                break;
                                            }
                                        }
                                        if (isSameAttrKey) {  //同一类点击切换
                                            if (selectAttrMap.size() == 1) {
                                                selectAttrMap.clear();
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                exchangeGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            } else {
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                exchangeGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            }
                                        } else {  //不同类的属性点击
                                            selectAttrMap.put(attrKey, attrItemBean);
                                            List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                            List<String> listStrings = getCompareStringList();
                                            referList.addAll(listStrings);
                                            itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                            exchangeGoodAttrAdapter.notifyDataSetChanged();
                                            getItemClickChangePic();
                                            isSameAttrKey = false;
                                            return;
                                        }
                                    }
                                } else {
                                    selectAttrMap.put(attrKey, attrItemBean);
                                    List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                    itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                    exchangeGoodAttrAdapter.notifyDataSetChanged();
                                    getItemClickChangePic();
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            @NonNull
            private List<String> getCompareStringList() {
                List<List<String>> compareOtherList = new ArrayList<>();
                for (String strKey : selectAttrMap.keySet()) {
                    Map<String, AttrItemBean> secordMap = new HashMap<>();
                    for (String secordKey : selectAttrMap.keySet()) {
                        if (!secordKey.equals(strKey)) {
                            secordMap.put(secordKey, selectAttrMap.get(secordKey));
                        }
                    }
                    List<String> secordItemList = getAllAlreadItemCanSelect(secordMap);
                    List<String> singleList = getSingleList(strKey);
                    List<String> itemAttrsList = new ArrayList<>();
                    for (int j = 0; j < secordItemList.size(); j++) {
                        if (singleList.contains(secordItemList.get(j))) {
                            itemAttrsList.add(secordItemList.get(j));
                        }
                    }
                    compareOtherList.add(itemAttrsList);
                }
                return getListStrings(compareOtherList);
            }

            @NonNull
            private List<String> getSingleList(String attrKey) {
                int indexInList = DataUtil.indexInList(attrKeyList, attrKey);
                List<String> singleList = new ArrayList<>();
                List<AttrItemBean> attrItemBeens = itemAttrList.get(indexInList);
                for (int j = 0; j < attrItemBeens.size(); j++) {
                    AttrItemBean itemBean = attrItemBeens.get(j);
                    singleList.add(itemBean.getAttrId());
                }
                return singleList;
            }

            private void getItemClickChangePic() {
                if (selectAttrMap != null && selectAttrMap.size() > 0) {
                    List<String> listId = new ArrayList<>();
                    for (String strKey : selectAttrMap.keySet()) {
                        AttrItemBean itemBean = selectAttrMap.get(strKey);
                        listId.add(itemBean.getAttrId());
                    }
                    List<GoodsAttrCollections> collectioneList = new ArrayList<>();
                    for (GoodsAttrCollections goodAttr : attrCollectionses) {
                        List<String> attrs = goodAttr.getAttrs();
                        if (attrs.containsAll(listId)) {
                            collectioneList.add(goodAttr);
                        }
                    }
                    if (collectioneList.get(0).getInnerprice() != null && !"0".equals(collectioneList.get(0).getInnerprice()) &&
                            collectioneList.get(0).getRedbean() != null && !collectioneList.get(0).getRedbean().equals("0")) {
                        tv_price.setText(collectioneList.get(0).getInnerprice() + "美豆");
                        tv_redprice.setText("+" + collectioneList.get(0).getRedbean() + "红豆");
                    } else if (collectioneList.get(0).getInnerprice().equals("0") && !collectioneList.get(0).getRedbean().equals("0")) {
                        tv_price.setText("");
                        tv_redprice.setText(collectioneList.get(0).getRedbean() + "红豆");
                    } else if (collectioneList.get(0).getRedbean().equals("0") && !collectioneList.get(0).getInnerprice().equals("0")) {
                        tv_price.setText(collectioneList.get(0).getInnerprice() + "美豆");
                        tv_redprice.setText("");
                    } else {
                        tv_price.setText("");
                        tv_redprice.setText("");
                    }

                    if (collectioneList.get(0).getStocknum() != null && !"".equals(collectioneList.get(0).getStocknum())) {
                        tvInventory.setText("库存:" + collectioneList.get(0).getStocknum() + "件");
                    } else {
                        tvInventory.setText("库存:0件");
                    }
                    if (null != collectioneList.get(0).getBackcashnum() && !"".equals(collectioneList.get(0).getBackcashnum()) && DataUtil.moreThanZero(collectioneList.get(0).getBackcashnum())) {
                        tvAward.setText("兑成奖：" + collectioneList.get(0).getBackcashnum() + "元");
                    } else {
                        tvAward.setText("");
                    }
                    if (null != collectioneList.get(0).getDaylimit() && !"".equals(collectioneList.get(0).getDaylimit()) && DataUtil.moreThanZero(collectioneList.get(0).getDaylimit())) {
                        tvDayLimit.setText("日限购" + collectioneList.get(0).getDaylimit() + "件");
                    } else {
                        tvDayLimit.setText("");
                    }
                    if (null != collectioneList.get(0).getUserlimit() && !"".equals(collectioneList.get(0).getUserlimit()) && DataUtil.moreThanZero(collectioneList.get(0).getUserlimit())) {
                        tvTotalLimit.setText("总限购" + collectioneList.get(0).getUserlimit() + "件");
                    } else {
                        tvTotalLimit.setText("");
                    }

                    Glide.with(context).load(Url.IMG_URL + collectioneList.get(0).getThumbnail()).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                } else {
                    Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0)).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                    tvInventory.setText("库存:999件");
                    tvAward.setText("");
                    tvDayLimit.setText("");
                    tvTotalLimit.setText("");
                }
            }

            @NonNull
            private List<String> getOnlyOneAttrCanSelect(AttrItemBean attrItemBean, String selectKey) {
                ArrayList<String> canSelects = getItemCanSelectAttr(attrItemBean);
                List<String> oneSelectCanAttr = new ArrayList<>();
                List<String> canAttrs = new ArrayList<>();
                for (String str : mapAllAttrs.keySet()) {
                    if (str.equals(selectKey)) {
                        List<AttrItemBean> attrItemBeenList = mapAllAttrs.get(str);
                        for (int j = 0; j < attrItemBeenList.size(); j++) {
                            oneSelectCanAttr.add(attrItemBeenList.get(j).getAttrId());
                        }
                    }
                }
                oneSelectCanAttr.addAll(canSelects);
                Set set = new HashSet();
                for (String str : oneSelectCanAttr) {
                    if (set.add(str)) {
                        canAttrs.add(str);  //去重后的可选的属性
                    }
                }
                return canAttrs;
            }

            @NonNull
            private List<String> getAllAlreadItemCanSelect(Map<String, AttrItemBean> selectAttrMap) {
                List<String> temporaryAttrId = new ArrayList<>();
                for (String str : selectAttrMap.keySet()) {
                    AttrItemBean attrBean = selectAttrMap.get(str);
                    temporaryAttrId.add(attrBean.getAttrId());
                }
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    List<String> attrs = goodAttr.getAttrs();
                    if (attrs.containsAll(temporaryAttrId)) {
                        collectionses.add(attrs);
                    }
                }
//                referList.addAll(collectionses.get(0));
//                for (int j = 0; j < collectionses.size(); j++) {
//                    referList.retainAll(collectionses.get(j));    //多数组取交集
//                }
                List<String> referList = getListStrings(collectionses);
                return referList;
            }

            @NonNull
            private List<String> getListStrings(List<List<String>> collectionses) {
                List<String> referList = new ArrayList<>();
                Set set = new HashSet();
                for (int i = 0; i < collectionses.size(); i++) {
                    List<String> list = collectionses.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        if (set.add(list.get(j))) {
                            referList.add(list.get(j));
                        }
                    }
                }
                return referList;
            }

            @NonNull
            private ArrayList<String> getItemCanSelectAttr(AttrItemBean attrItemBean) {
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    if (goodAttr.getAttrs().contains(attrItemBean.getAttrId())) {
                        collectionses.add(goodAttr.getAttrs());
                    }
                }
                Set set = new HashSet();
                ArrayList<String> canSelects = new ArrayList<>();
                for (List<String> collection : collectionses) {
                    for (String attr : collection) {
                        if (set.add(attr)) {
                            canSelects.add(attr);
                        }
                    }
                }
                return canSelects;
            }
        };
        popupWindow_view = getLayoutInflater().inflate(R.layout.change_base_cart_info, null);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        ivImg = (ImageView) popupWindow_view.findViewById(R.id.ivImg);
        ImageView ivCancel = (ImageView) popupWindow_view.findViewById(R.id.ivCancel);
        TextView tvName = (TextView) popupWindow_view.findViewById(R.id.tvName);
        tvInventory = (TextView) popupWindow_view.findViewById(R.id.tvInventory);
        tvAward = (TextView) popupWindow_view.findViewById(R.id.tvAward);
        tvDayLimit = (TextView) popupWindow_view.findViewById(R.id.tvDayLimit);
        tvTotalLimit = (TextView) popupWindow_view.findViewById(R.id.tvTotalLimit);
        tv_price = (TextView) popupWindow_view.findViewById(R.id.tv_reward_price);
        tv_redprice = (TextView) popupWindow_view.findViewById(R.id.tv_reward_redprice);
        TextView tvAdd = (TextView) popupWindow_view.findViewById(R.id.tvAdd);
        TextView tvSub = (TextView) popupWindow_view.findViewById(R.id.tvSub);
        final EditText etNum = (EditText) popupWindow_view.findViewById(R.id.etNum);
        TextView tvSure_attr = (TextView) popupWindow_view.findViewById(R.id.tvSure_attr);
        ListView lvList = (ListView) popupWindow_view.findViewById(R.id.lvList);
        final LinearLayout type1 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type1);  //当面付
        final TextView tv1 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv1);
        final TextView tv11 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv11);
        final LinearLayout type2 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type2);   //自提
        final TextView tv2 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv2);
        final TextView tv22 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv22);
        final LinearLayout type3 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type3);   //邮寄
        final TextView tv3 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv3);
        final TextView tv33 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv33);
        TextView tv_amountofmail = (TextView) popupWindow_view.findViewById(R.id.tv_amountofmail);
        if (detailResult.getShopInfo() != null) {
            if (detailResult.getShopInfo().getAmountofmail() != null && !"".equals(detailResult.getShopInfo().getAmountofmail())) {
                if (!"0".equals(detailResult.getShopInfo().getAmountofmail())) {
                    tv_amountofmail.setText("本店满" + detailResult.getShopInfo().getAmountofmail() + "红豆包邮");
                    tv33.setText("(快递:" + goodsInfo.getPostage() + "红豆)");
                } else if (!DataUtil.moreThanZero(goodsInfo.getPostage())) {
                    tv_amountofmail.setText("本店商品包邮");
                    tv33.setText("(快递:0红豆)");
                } else {
                    tv_amountofmail.setText("本店商品不包邮");
                    tv33.setText("(快递:" + goodsInfo.getPostage() + "红豆)");
                }
            }
        }


        RelativeLayout relative2 = (RelativeLayout) popupWindow_view.findViewById(R.id.relative2);
        WindowManager manger = (WindowManager) getSystemService(RewardCoinDetailActivity.WINDOW_SERVICE);
        Display display = manger.getDefaultDisplay();
        RelativeLayout rl_ctx = (RelativeLayout) popupWindow_view.findViewById(R.id.rl_ctx);
        ViewGroup.LayoutParams layoutParams = rl_ctx.getLayoutParams();
        layoutParams.height = 4 * display.getHeight() / 5;
        if (goodsInfo.getImages() != null && goodsInfo.getImages().size() > 0) {
            Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0))
                    .placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
        }
        tvName.setText(goodsInfo.getName());


        if (goodsInfo.getInnerprice() != null && !"0".equals(goodsInfo.getInnerprice()) &&
                goodsInfo.getRedbeanprice() != null && !goodsInfo.getRedbeanprice().equals("0")) {
            tv_price.setText(goodsInfo.getInnerprice() + "美豆");
            tv_redprice.setText("+" + goodsInfo.getRedbeanprice() + "红豆");
        } else if (goodsInfo.getInnerprice().equals("0") && !goodsInfo.getRedbeanprice().equals("0")) {
            tv_price.setText("");
            tv_redprice.setText(goodsInfo.getRedbeanprice() + "红豆");
        } else if (goodsInfo.getRedbeanprice().equals("0") && !goodsInfo.getInnerprice().equals("0")) {
            tv_price.setText(goodsInfo.getInnerprice() + "美豆");
            tv_redprice.setText("");
        } else {
            tv_price.setText("");
            tv_redprice.setText("");
        }

        switch (goodsInfo.getGetermethod()) {
            case "1":  //邮寄
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        if (stateType3) {
                            DataUtil.isExchangeSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                    }
                });
                break;
            case "2":   //自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        if (stateType2) {
                            DataUtil.isExchangeSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                    }
                });
                break;
            case "3":   //邮寄+自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType3 = false;
                        if (stateType2) {
                            DataUtil.isExchangeSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType2 = false;
                        if (stateType3) {
                            DataUtil.isExchangeSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                break;
        }

        tvSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num > 1) {
                    num--;
                } else {
                    showShortToast("最少购买一件");
                }
                etNum.setText(String.valueOf(num));
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num <= 100) {
                    num++;
                } else {
                    showShortToast("购买数量不能大于100");
                }
                etNum.setText(String.valueOf(num));
            }
        });

        //立即购买
        tvSure_attr.setOnClickListener(new View.OnClickListener() {
            private boolean containsAll;   //进入确认支付界面
            private boolean b;

            @Override
            public void onClick(View view) {
                if (stateType1 || stateType2 || stateType3) {
                    List<String> attrIdList = new ArrayList<>();
                    List<String> keySelect = new ArrayList<>();
                    List<String> itemAttrs = new ArrayList<>();
                    String jsonAttrId = "[";     //  {"password":"1234","username":"cxl"}
                    for (String attr : selectAttrMap.keySet()) {
                        AttrItemBean s = selectAttrMap.get(attr);
                        keySelect.add(attr);
                        attrIdList.add(s.getAttrId());
                        itemAttrs.add(s.getName());
                        jsonAttrId = jsonAttrId + "\"" + s.getAttrId() + "\",";
                    }
                    String json = jsonAttrId.substring(0, jsonAttrId.length() - 1) + "]";
                    if (allList != null && allList.size() > 0) {
                        for (int i = 0; i < allList.size(); i++) {
                            AttrsSelect attrsSelect = allList.get(i);
                            Map<String, List<String>> map = attrsSelect.getItemMaps();
                            List<String> mapList = new ArrayList<>();
                            List<String> mapAttrId = new ArrayList<>();
                            for (String attr2 : map.keySet()) {
                                mapList.add(attr2);
                                List<String> list = map.get(attr2);
                                mapAttrId.addAll(list);
                            }
                            b = DataUtil.equalList(keySelect, mapList);
                            containsAll = mapAttrId.containsAll(attrIdList);
                            if (b && containsAll) {
                                String trim = tvInventory.getText().toString().trim();
                                String substring = trim.substring(trim.indexOf(":") + 1, trim.length() - 1);
                                if (DataUtil.moreThanZero(substring)) {
                                    popupWindow.dismiss();
                                    attrsSelect.setName(goodsInfo.getName());
                                    attrsSelect.setGoodsnum(etNum.getText().toString().trim());
                                    attrsSelect.setPostage(goodsInfo.getPostage());
                                    attrsSelect.setGetermethod(goodsInfo.getGetermethod());
                                    attrsSelect.setAttrlist(json);
                                    attrsSelect.setItemGoodAttrs(itemAttrs);
                                    Intent intent = new Intent(context, ExchangePayActivity.class);
                                    intent.putExtra("attrs", attrsSelect);
                                    if (stateType2) {
                                        intent.putExtra("post", 0);  // 自提
                                    } else if (stateType3) {
                                        intent.putExtra("post", 1);  // 邮寄
                                    }
//                                    else if (stateType1) {
//                                        intent.putExtra("post", 2);  // 同城免邮
//                                    }
                                    startActivity(intent);
                                    return;
                                } else {
                                    showShortToast("库存不足,无法支付");
                                }
                            }
                        }
                    }
                    if (!(b && containsAll)) {
                        showShortToast("请把该商品属性选完整");
                    }
                } else {
                    showShortToast("请选择支付方式");
                }

            }
        });

        if (attr != null && !"".equals(attr)) {
            Iterator<String> keys = attr.keys();
            List<String> keyList = new ArrayList<>();
            itemAttrList = new ArrayList<>();
            mapAllAttrs = new HashMap<>();
            while (keys.hasNext()) {
                String next = keys.next();
                keyList.add(next);
                JSONArray jsonArray = attr.optJSONArray(next); //  [ ["十边形","att2929593f9c024ddd5"], ["六边形","att7364593f9960eb35b"] ]
                List<AttrItemBean> itemList = new ArrayList<>();
                for (int k = 0; k < jsonArray.length(); k++) {
                    try {
                        JSONArray jsonAllItemArray = (JSONArray) jsonArray.get(k);
                        AttrItemBean attrItemBean = new AttrItemBean();
                        for (int l = 0; l < jsonAllItemArray.length(); l++) {
                            if (l == 0) {
                                String attrName = (String) jsonAllItemArray.get(l);
                                attrItemBean.setName(attrName);
                            } else if (l == 1) {
                                String attrId = (String) jsonAllItemArray.get(l);
                                attrItemBean.setAttrId(attrId);
                            }
                            attrItemBean.setStates("1");
                        }
                        itemList.add(attrItemBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                itemAttrList.add(itemList);
                mapAllAttrs.put(next, itemList);
            }
            if (keyList != null && keyList.size() > 0 && detailResult.getGoodsAttrCollection() != null &&
                    detailResult.getGoodsAttrCollection().size() > 0) {
                exchangeGoodAttrAdapter = new ExchangeGoodAttrAdapter(context, handler, keyList, itemAttrList);
                lvList.setAdapter(exchangeGoodAttrAdapter);
                exchangeGoodAttrAdapter.notifyDataSetChanged();
            }
        }
        //消失
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    isRemove = false;
                    popupWindow = null;
                }
            }
        });
        if (!popupWindow.isShowing()) {
            isRemove = false;
        }
        popupWindow_view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int[] location = new int[2];
        linearBottom.getLocationOnScreen(location);
        popupWindow.showAtLocation(linearBottom, Gravity.BOTTOM, location[0], location[1] - popupWindow.getHeight());
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (null != popupWindow && popupWindow.isShowing())
            popupWindow.dismiss();

        super.onDestroy();
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(clearWeedDetailShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;


                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                UMWeb mUMWeb = new UMWeb(Url.IMG_URL + "/Home/pars/offline_get_url?id=" + id);
                mUMWeb.setTitle("正常消费，额外再获一倍奖励=免费消费");
                mUMWeb.setDescription("推荐一个好商品;超级优惠,不用现金美豆即可抵钱花!");
                mUMWeb.setThumb(new UMImage(ClearWeedDetailActivity.this, R.mipmap.logo));
                new ShareAction(ClearWeedDetailActivity.this).setPlatform(platform)
                        .setCallback(umShareListener)
                        .withMedia(mUMWeb)
                        .share();

                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };


}
